package de.tewdreyer.android.quaffed;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.view.View;

import java.util.ArrayList;

public class BarChart extends View implements Graph {
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private int mPadding = 10;

    private ArrayList<String> mKeys;
    private ArrayList<Double> mValues;

    private AxisImpl mXAxis;
    private AxisImpl mYAxis;


    public BarChart(Context context, ArrayList<String> keys, ArrayList<Double> values) {
        super(context);

        mPaint.setColor(0xFF000000);

        mKeys = keys;
        mValues = values;
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        mXAxis = new AxisImpl(getLeft() + mPadding, getBottom() - mPadding,
                getRight() - mPadding, getBottom() - mPadding);
        mYAxis = new AxisImpl(getLeft() + mPadding, getBottom() - mPadding,
                getLeft() + mPadding, getTop() + mPadding);

        mXAxis.setNumSections(mKeys.size());

        drawData(canvas, mKeys, mValues);
    }

    public void drawData(Canvas canvas, ArrayList<String> keys, ArrayList<Double> values) {
        if (keys.size() != values.size())
            return;

        mXAxis.draw(canvas);
        mYAxis.draw(canvas);

        double maxValue = 0;
        for (double value : values) {
            if (value > maxValue)
                maxValue = value;
        }

        int heightMaxValue = Integer.MAX_VALUE;
        for (Point p : mYAxis.getIntersectionPoints()) {
            if (p.y < heightMaxValue)
                heightMaxValue = p.y;
        }

        int i = 0;
        for (Point p : mXAxis.getSectionMidPoints()) {
            int height = (int) (values.get(i) / maxValue * (p.y - heightMaxValue));
            canvas.drawRect(p.x - 7, p.y - height, p.x + 7, p.y, mPaint);
            i++;
        }
    }
}
